var gulp = require('gulp');
var gulpWebpack = require("gulp-webpack");
var proxy = require('http-proxy-middleware');
var webpackConfig = require("./webpack.config");
var webpackDevConfig = require("./webpack.dev.config");
var del = require('del');
var livereload = require('gulp-livereload');
var connect = require('gulp-connect');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var less = require('gulp-less');
var cssmin = require('gulp-minify-css');
var runSequence = require('run-sequence');
var fs = require('fs');
var rootPath = './webapp/';//根据项目实际路径修改
var publishPath = './';

var cssPath = [rootPath+'styles/**/*.css', rootPath+'modules/**/*.css'];
var jsPath = [rootPath+'index.js', rootPath+'core/**/*.js', rootPath+'modules/**/*.js'];
var viewPath = [rootPath+'modules/**/*.html', rootPath+'modules/**/*.tpl'];
var entryPath = [rootPath+'index.html'];
var filesPath = [rootPath+'images/**/*.*'];

gulp.task('clean', function() {
});

gulp.task('watch', function() {
  livereload.listen();
  gulp.watch(jsPath, ['buildjs']);
  gulp.watch(cssPath, ['buildcss']);
  gulp.watch(viewPath, ['buildjs']);
  gulp.watch(entryPath, ['buildhtml']);
});

gulp.task('buildcss', function(){
    return gulp.src(cssPath)
        .pipe(concat('main.css'))
        .pipe(cssmin())
        .pipe(gulp.dest(publishPath))
        .pipe(livereload());
});

gulp.task('buildjs', function(){
    return gulp.src(jsPath)
        .pipe(gulpWebpack(webpackDevConfig))
        .pipe(gulp.dest(publishPath))
        .pipe(livereload());
});

gulp.task('buildjsproduct', function(){
    return gulp.src(jsPath)
        .pipe(gulpWebpack(webpackConfig))
        .pipe(uglify())
        .pipe(gulp.dest(publishPath))
        .pipe(livereload());
});

gulp.task('buildhtml', function(){
    return gulp.src(entryPath)
        .pipe(gulp.dest(publishPath))
        .pipe(livereload());
});

gulp.task('copy', function(){
    return gulp.src(filesPath)
        .pipe(gulp.dest(publishPath + 'images/'));
});

gulp.task('build', function(callback){
    runSequence('clean', 'copy', ['buildjs', 'buildcss', 'buildhtml'], 'watch', callback);
});

gulp.task('buildproduct', function(callback){
    runSequence('clean', 'copy', ['buildjsproduct', 'buildcss', 'buildhtml'], callback);
});

gulp.task('serve', function(){
    connect.server({
      port: 9001/*,
	  middleware: function() {
          return [
              proxy('/', {
                  target: 'http://172.16.40.36:8882',
                  changeOrigin:true
              })
          ];
      }*/
    });
});

gulp.task('default',['build', 'serve'], function(){

});

gulp.task('publish',['buildproduct'], function(){

});
